﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "工艺流程管理";
    Layout = null;
}
<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
<style>
    .layui-table-cell {
        white-space: pre-line;
        word-break: break-all;
        max-width: 300px;
    }

    .layui-form-label {
        width: 110px;
    }

    .layui-input-block {
        margin-left: 140px;
    }

    .layui-layer-content .layui-form-item {
        margin-bottom: 18px;
    }

    .layui-btn-danger {
        background-color: #ff5722;
    }

    .layui-table-view .layui-table-empty {
        color: #999;
        font-size: 16px;
    }
</style>
<div class="layui-card">
    <div class="layui-card-header">
        工艺流程管理
        <button type="button" class="layui-btn layui-btn-sm" id="btnAdd">
            <i class="layui-icon">&#xe654;</i> 新增
        </button>
        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="btnExport">
            <i class="layui-icon">&#xe601;</i> 导出
        </button>
    </div>
    <div class="layui-card-body">
        <table id="workmanshipTable" lay-filter="workmanshipTable"></table>
    </div>
</div>

<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<div id="editDialog" style="display: none; padding: 20px;">
    <form class="layui-form" lay-filter="editForm" id="editForm">
        <input type="hidden" name="id" />
        <div class="layui-form-item">
            <label class="layui-form-label">工艺路线编号</label>
            <div class="layui-input-block">
                <input type="text" name="workmanshipCode" id="workmanshipCodeInput" required lay-verify="required" placeholder="请输入工艺路线编号" class="layui-input" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">工艺路线名称</label>
            <div class="layui-input-block">
                <input type="text" name="workmanshipName" required lay-verify="required" placeholder="请输入工艺路线名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">工艺路线说明</label>
            <div class="layui-input-block">
                <textarea name="workmanshipDescribe" placeholder="请输入工艺路线说明" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input type="checkbox" name="isEnable" lay-skin="switch" lay-text="是|否" value="true">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="context" placeholder="请输入备注" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item" style="text-align: center;">
            <button class="layui-btn" lay-submit lay-filter="submitEdit" id="saveBtn">保存</button>
            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
        </div>
    </form>
</div>

<script>
    layui.use(['table', 'form', 'layer'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.$;

        // 渲染表格（分页）
        table.render({
            elem: '#workmanshipTable',
            url: '/Workmanship/GetWorkmanship',
            method: 'GET',
            page: true,
            request: {
                pageName: 'pageIndex', // 页码参数名
                limitName: 'pageSize'  // 每页数量参数名
            },
            limits: [5, 10, 20, 50, 100],
            limit: 10,
            text: {none: '暂无数据'},
            cols: [[
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'workmanshipCode', title: '工艺路线编号', minWidth: 120},
                {field: 'workmanshipName', title: '工艺路线名称', minWidth: 120},
                {field: 'workmanshipDescribe', title: '工艺路线说明', minWidth: 180},
                {field: 'isEnable', title: '是否启用', width: 100, templet: function(d){
                    return d.isEnable ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge layui-bg-gray">否</span>';
                }},
                {field: 'context', title: '备注', minWidth: 120},
                {title: '操作', width: 180, toolbar: '#tableBar', fixed: 'right'}
            ]]
        });

        // 监听工具条
        table.on('tool(workmanshipTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                openEditDialog(data);
            } else if(obj.event === 'del'){
                layer.confirm('确定删除该工艺流程吗？', {icon: 3, title:'提示'}, function(index){
                    $.ajax({
                        url: '/Workmanship/DeleteWorkmanship?workmanshipId=' + data.id,
                        type: 'DELETE',
                        success: function(res){
                            if(res > 0){
                                layer.msg('删除成功');
                                obj.del();
                            } else {
                                layer.msg('删除失败');
                            }
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 新增按钮
        $('#btnAdd').on('click', function(){
            openEditDialog();
        });

        // 导出按钮
        $('#btnExport').on('click', function(){
            exportToExcel();
        });

        // 随机生成工艺路线编号函数
        function generateRandomCode() {
            // 例如 GX+时间戳+三位随机数
            return 'GX' + Date.now() + Math.floor(Math.random() * 900 + 100);
        }

        // 打开编辑/新增弹窗
        function openEditDialog(data) {
            // 清空表单
            form.val('editForm', {
                id: '',
                workmanshipCode: '',
                workmanshipName: '',
                workmanshipDescribe: '',
                isEnable: false,
                context: ''
            });
            layer.open({
                type: 1,
                title: data ? '编辑工艺流程' : '新增工艺流程',
                area: ['500px', '520px'],
                content: $('#editDialog'),
                success: function(){
                    if(!data){
                        // 新增时自动生成编号且只读
                        var code = generateRandomCode();
                        $('#workmanshipCodeInput').val(code).prop('readonly', true);
                    }else{
                        // 编辑时允许手动输入
                        $('#workmanshipCodeInput').prop('readonly', false);
                        form.val('editForm', {
                            id: data.id,
                            workmanshipCode: data.workmanshipCode,
                            workmanshipName: data.workmanshipName,
                            workmanshipDescribe: data.workmanshipDescribe,
                            isEnable: data.isEnable,
                            context: data.context
                        });
                    }
                },
                end: function(){
                    $('#editForm')[0].reset();
                }
            });
        }

        // 提交编辑/新增
        form.on('submit(submitEdit)', function(formData){
            var field = formData.field;
            field.isEnable = field.isEnable === 'true' || field.isEnable === true;
            var url = field.id ? '/Workmanship/UpdateWorkmanship' : '/Workmanship/AddWorkmanship';
            var $btn = $('#saveBtn');
            $btn.addClass('layui-btn-disabled').attr('disabled', true).text('保存中...');
            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    id: field.id ? parseInt(field.id) : 0,
                    workmanshipCode: field.workmanshipCode,
                    workmanshipName: field.workmanshipName,
                    workmanshipDescribe: field.workmanshipDescribe,
                    isEnable: field.isEnable,
                    context: field.context
                },
                success: function(res){
                    if(res > 0){
                        layer.msg('保存成功');
                        layer.closeAll('page');
                        table.reload('workmanshipTable');
                    } else {
                        layer.msg('保存失败');
                    }
                },
                error: function(){
                    layer.msg('操作失败，请重试');
                },
                complete: function(){
                    $btn.removeClass('layui-btn-disabled').attr('disabled', false).text('保存');
                }
            });
            return false;
        });

        // 支持回车提交
        $(document).on('keydown', function(e){
            if(e.keyCode === 13 && $('.layui-layer').length){
                $('#saveBtn').click();
            }
        });

        // 导出Excel功能
        function exportToExcel() {
            var $btn = $('#btnExport');
            $btn.addClass('layui-btn-disabled').attr('disabled', true).text('导出中...');
            
            $.ajax({
                url: '/Workmanship/GetWorkmanship',
                type: 'GET',
                data: {
                    pageIndex: 1,
                    pageSize: 99999 // 获取所有数据
                },
                success: function(response) {
                    if (response && response.data && response.data.length > 0) {
                        // 创建Excel数据
                        var excelData = [
                            ['ID', '工艺路线编号', '工艺路线名称', '工艺路线说明', '是否启用', '备注'] // 表头
                        ];
                        
                        // 添加数据行
                        response.data.forEach(function(item) {
                            excelData.push([
                                item.id,
                                item.workmanshipCode,
                                item.workmanshipName,
                                item.workmanshipDescribe || '',
                                item.isEnable ? '是' : '否',
                                item.context || ''
                            ]);
                        });
                        
                        // 使用layui的util.toDateString格式化当前时间作为文件名
                        var fileName = '工艺流程数据_' + getFormattedDate() + '.csv';
                        
                        // 转换为CSV格式并下载
                        downloadCSV(excelData, fileName);
                        
                        layer.msg('导出成功');
                    } else {
                        layer.msg('暂无数据可导出');
                    }
                },
                error: function() {
                    layer.msg('导出失败，请重试');
                },
                complete: function() {
                    $btn.removeClass('layui-btn-disabled').attr('disabled', false).html('<i class="layui-icon">&#xe601;</i> 导出');
                }
            });
        }
        
        // 获取格式化日期
        function getFormattedDate() {
            var now = new Date();
            var year = now.getFullYear();
            var month = String(now.getMonth() + 1).padStart(2, '0');
            var day = String(now.getDate()).padStart(2, '0');
            var hours = String(now.getHours()).padStart(2, '0');
            var minutes = String(now.getMinutes()).padStart(2, '0');
            var seconds = String(now.getSeconds()).padStart(2, '0');
            return year + month + day + '_' + hours + minutes + seconds;
        }
        
        // 下载CSV文件
        function downloadCSV(data, filename) {
            var csvContent = '';
            data.forEach(function(row) {
                var rowContent = row.map(function(field) {
                    // 处理包含逗号、引号或换行符的字段
                    if (typeof field === 'string' && (field.includes(',') || field.includes('"') || field.includes('\n'))) {
                        return '"' + field.replace(/"/g, '""') + '"';
                    }
                    return field;
                }).join(',');
                csvContent += rowContent + '\n';
            });
            
            // 添加BOM头以支持中文
            var BOM = '\uFEFF';
            var blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
            
            // 创建下载链接
            var link = document.createElement('a');
            if (link.download !== undefined) {
                var url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    });
</script>

